﻿using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Frm.DataProcess
{
    public partial class RuleWordUpdate : Form
    {
        /// <summary>
        /// 路径
        /// </summary>
        public string XmlPath { get; set; }

        /// <summary>
        /// 规则词
        /// </summary>
        public string RuleWord { get; set; }

        /// <summary>
        /// ewID
        /// </summary>
        public string EwID { get; set; }

        /// <summary>
        /// ruleSynWord
        /// </summary>
        public string RuleSynWord { get; set; }

        /// <summary>
        /// Ccid
        /// </summary>
        public string Ccid { get; set; }

        /// <summary>
        /// 存放最后的词
        /// </summary>
        Dictionary<string, string> dicRuleWordFinal = new Dictionary<string, string>();
        SYS_Element_Ruleword_RelBLL serrBll = new SYS_Element_Ruleword_RelBLL();

        public RuleWordUpdate(string xmlPath, string ruleWord, string ewID, string ruleSynWord, string ccid)
        {
            InitializeComponent();
            XmlPath = lblPath.Text = xmlPath;
            RuleWord = ruleWord;
            RuleSynWord = ruleSynWord;
            EwID = ewID;
            Ccid = ccid;
            DataTable dt = new DataTable();
            dt.Columns.Add("gzc");
            string[] strs = RuleWord.Split(new char[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
            if(strs.Length>0)
            {
                foreach (var item in strs)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = item;
                    dt.Rows.Add(dr);
                }
                dataGridView1.DataSource = dt;
            }           
        }

        private void btnCanel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// 确定按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)dataGridView1.DataSource;
            if (dt != null && dt.Rows.Count > 0)
            {
                Dictionary<string, string> dicRuleWord = new Dictionary<string, string>();
                StringBuilder ruleW = new StringBuilder();
                if (!string.IsNullOrEmpty(RuleSynWord))
                {
                    //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
                    string[] res = RuleSynWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                    if (res.Length > 0)
                    {

                        foreach (var item in res)
                        {
                            string[] lis = item.Split(':');
                            if (lis.Length > 0)
                            {
                                if (!string.IsNullOrWhiteSpace(lis[0]))
                                {
                                    if (!dicRuleWord.ContainsKey(lis[0]))
                                    {
                                        dicRuleWord.Add(lis[0], lis[1] + ":" + lis[2]);
                                    }
                                }
                            }

                        }
                    }
                }
                StringBuilder sb = new StringBuilder();
                foreach (DataRow item in dt.Rows)
                {
                    string[] strs = item[0].ToString().Trim().Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                    if (strs.Length > 0)
                    {

                        foreach (var ite in strs)
                        {
                            if (dicRuleWord.ContainsKey(ite)&&!dicRuleWordFinal.ContainsKey(ite))
                            {
                                dicRuleWordFinal.Add(ite, dicRuleWord[ite]);
                            }
                            else if(!dicRuleWordFinal.ContainsKey(ite))
                            {
                                sb.Append(ite + ",");
                            }
                            ruleW.Append(ite + "，");
                        }
                        ruleW = new StringBuilder(ruleW.ToString().Remove(ruleW.Length - 1, 1).Trim());
                        ruleW.Append("；");
                    }
                }
                if (sb.ToString().Length > 0)
                {
                    string st = sb.ToString().Remove(sb.ToString().Length - 1, 1).ToString().Trim();
                    CaseCauseBLL casebll = new CaseCauseBLL();
                    GetWordTY(st, casebll.IsParentRealation1(Ccid).CC_ID);
                }
                StringBuilder rule = new StringBuilder();
                if (dicRuleWordFinal.Keys.Count > 0)
                {
                    foreach (var item in dicRuleWordFinal.Keys)
                    {
                        rule.Append(item + ":" + dicRuleWordFinal[item] + "$");
                    }
                }
                SYS_Element_Ruleword_Rel ser = new SYS_Element_Ruleword_Rel();
                ser.EW_ID = EwID;
                ser.Ruleword = ruleW.ToString().Remove(ruleW.Length - 1, 1).Trim();
                ser.Rule_Synforbidword = rule.ToString().Remove(rule.Length - 1, 1).Trim();
                serrBll.UpdateElementWord(ser);
                MessageBox.Show("修改成功！");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("请将规则词补充完整后再试！");
                return;
            }
        }

        //思路：先把分词拆开放到dic中并进行比较，原有的留下，新增的添加，然后组合好回填
        //    if (!string.IsNullOrEmpty(rtbRuleWord.Text.Trim()))
        //    {
        //        Dictionary<string, string> dicRuleWord = new Dictionary<string, string>();

        //        if (!string.IsNullOrEmpty(RuleSynWord))
        //        {
        //            //法律::$采用:采取,选取,选用,选择,采纳,抉择,选定,采选:$书面形式::$订立合同:签订合同,合同订立,合同签订:$
        //            string[] res = RuleSynWord.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
        //            if (res.Length > 0)
        //            {

        //                foreach (var item in res)
        //                {
        //                    string[] lis = item.Split(':');
        //                    if (lis.Length > 0)
        //                    {
        //                        if (!string.IsNullOrWhiteSpace(lis[0]))
        //                        {
        //                            if (!dicRuleWord.ContainsKey(lis[0]))
        //                            {
        //                                dicRuleWord.Add(lis[0], lis[1] + ":" + lis[2]);
        //                            }
        //                        }
        //                    }

        //                }
        //            }
        //        }
        //        string[] strs = rtbRuleWord.Text.Trim().Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
        //        StringBuilder ruleW = new StringBuilder();
        //        if (strs.Length > 0)
        //        {
        //            StringBuilder sb = new StringBuilder();
        //            foreach (var item in strs)
        //            {
        //                if (dicRuleWord.ContainsKey(item))
        //                {
        //                    dicRuleWordFinal.Add(item, dicRuleWord[item]);
        //                }
        //                else
        //                {
        //                    sb.Append(item + ",");
        //                }
        //                ruleW.Append(item + "，");
        //            }
        //            if (sb.ToString().Length > 0)
        //            {
        //                string st = sb.ToString().Remove(sb.ToString().Length - 1, 1).ToString().Trim();
        //                CaseCauseBLL casebll = new CaseCauseBLL();
        //                GetWordTY(st, casebll.IsParentRealation1(Ccid).CC_ID);
        //            }
        //            StringBuilder rule = new StringBuilder();
        //            if (dicRuleWordFinal.Keys.Count > 0)
        //            {
        //                foreach (var item in dicRuleWordFinal.Keys)
        //                {
        //                    rule.Append(item + ":" + dicRuleWordFinal[item] + "$");
        //                }
        //            }
        //            SYS_Element_Ruleword_Rel ser = new SYS_Element_Ruleword_Rel();
        //            ser.EW_ID = EwID;
        //            ser.Ruleword = ruleW.ToString().Remove(ruleW.Length - 1, 1).Trim();
        //            ser.Rule_Synforbidword= rule.ToString().Remove(rule.Length - 1, 1).Trim();
        //            serrBll.UpdateElementWord(ser);
        //            MessageBox.Show("修改成功！");
        //            this.DialogResult = DialogResult.OK;
        //            this.Close();
        //        }
        //    }
        //    else
        //    {
        //        MessageBox.Show("请将规则词补充完整后再试！");
        //        rtbRuleWord.Focus();
        //        return;
        //    }

        //}

        /// <summary>
        /// 获取节点分词
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ccid"></param>
        /// <param name="caseCauseCode"></param>
        public void GetWordTY(string content, string caseCauseCode)
        {
            try
            {
                SYS_SiftBdSynBLL ssbsbll = new SYS_SiftBdSynBLL();
                DataTable dtsbds = ssbsbll.GetSiftBdSyn();
                RequestWord rc = new RequestWord() { content = content.Trim(), caseCauseCode = caseCauseCode, industryCode = "通用", isSegment = "否" };
                string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
                WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
                if (model.result.code == "1")
                {
                    List<string> segments = new List<string>();
                    List<thesaurusModel> thesaurusModels = model.body;
                    if (thesaurusModels.Count > 0)
                    {
                        //分词的组合
                        foreach (thesaurusModel item in thesaurusModels)
                        {
                            if (segments.Contains(item.segmentWord))
                            {
                                continue;
                            }
                            else
                            {
                                segments.Add(item.segmentWord);
                                if (!dicRuleWordFinal.ContainsKey(item.segmentWord))
                                {
                                    dicRuleWordFinal.Add(item.segmentWord, "");
                                }
                            }
                            StringBuilder sbTy = new StringBuilder();
                            StringBuilder sbJy = new StringBuilder();
                            //同义词
                            if (item.thesaurusWrods.Count > 0)
                            {
                                //每一个分词的组合
                                if (item.thesaurusWrods != null)
                                {
                                    foreach (thesaurusWrodModel item1 in item.thesaurusWrods)
                                    {
                                        if (dtsbds != null && dtsbds.Rows.Count > 0 && dtsbds.Select(" Ruleword='" + item.segmentWord + "' and BdSyn='" + item1.thesaurusWrod + "'").Length > 0)
                                        {
                                        }
                                        else
                                        {
                                            sbTy.Append(item1.thesaurusWrod + ",");
                                        }
                                    }
                                }
                            }
                            if (item.forbiddenWords.Count > 0)
                            {
                                //每一个分词的组合

                                foreach (wordModel item1 in item.forbiddenWords)
                                {
                                    if (item1.word != null)
                                    {
                                        foreach (string item2 in item1.word)
                                        {
                                            sbJy.Append(item2 + ",");

                                        }
                                    }
                                }
                            }
                            string ty = sbTy.ToString().Length > 0 ? sbTy.ToString().Remove(sbTy.ToString().Length - 1, 1).ToString().Trim() : "";
                            string jy = sbJy.ToString().Length > 0 ? sbJy.ToString().Remove(sbJy.ToString().Length - 1, 1).ToString().Trim() : "";
                            dicRuleWordFinal[item.segmentWord] = ty + ":" + jy;
                        }
                    }
                }
                else if (model.result.code == "0")
                {
                    Log.WriteLog("添加失败！content:" + content + model.result.message);
                }

            }
            catch (Exception ex)
            {
                Log.WriteLog("调用获取词库分词接口发生错误：content:" + content + ex.Message);
            }
        }
    }
}
